package edu.mse.camel.client.session.wizards;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;

import edu.mse.camel.client.core.session.event.PBInitiationEvent;
import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.events.server.CreateSessionEvent;
import edu.mse.camel.client.session.team.TeamList;
import edu.mse.camel.client.session.util.FilePublisherUtil;

public class CreateSessionWizard extends Wizard implements INewWizard {

	private static final String POSTERBOARD_ID = "edu.mse.camel.client.posterboard.ui.editor.PosterBoard";
	private static final String WHITEBOARD_ID = "edu.mse.camel.client.whiteboard.diagram.part.WhiteboardDiagramEditorID";
	private static final String PROJECT_NAME_SEPARATOR = "_";
	public static final String PLATFORM_PREFIX = "platform:resource/"; 
	public static final String POSTERBOARD_EXT = ".posterboard";
	public static final String WHITEBOARD_EXT = ".whiteboard";
	
	// wizard pages
	TitleDescPage titleDescPage;
	ModelDiagramPage modelDiagramPage;
	
	// the information for creating a session
	SessionModel model;
	
	// workbench selection when the wizard was started
	protected IStructuredSelection selection;
	
	// flag indicated whether the wizard can be completed or not 
	protected boolean isCompleted = false;
	protected boolean isNewWhiteboard = false;

	// the workbench instance
	protected IWorkbench workbench;
	
	protected IWorkspaceRoot root;

	/*
	 * constructor for create session wizard
	 */
	public CreateSessionWizard() {
		super();
		model = new SessionModel();
		root = ResourcesPlugin.getWorkspace().getRoot();
	}

	@Override
	public void addPages() {
		
		titleDescPage = new TitleDescPage(workbench, selection);
		addPage(titleDescPage);
		modelDiagramPage = new ModelDiagramPage("");
		addPage(modelDiagramPage);
		
	}

	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {

		this.workbench = workbench;
		this.selection = selection;
		
	}

	@Override
	public boolean canFinish() {
		if (this.getContainer().getCurrentPage() == titleDescPage)
			return false;
		return isCompleted;
	}

	@Override 
	public boolean performFinish() {

		setView();

		CreateSessionEvent cse = new CreateSessionEvent(model.title, model.description);
		EventManager.getInstance().dispatchEventSynchronous(cse, true);

		if (cse.isOpSuccessful()) {
			
			//setMe
			TeamList.getInstance().createSession();
			
//				create temporary project
			IProject iProject = createTempProject();
			
			// publish local event for poster board
			// We change the name of the diagram and model in the session model
			// to the temporary files while copying
			PBInitiationEvent pbie;
			String wbName;
			if(model.selectedWhiteboard == null){
				wbName = model.title + WHITEBOARD_EXT;
				isNewWhiteboard = true;
			} else {
				wbName = model.selectedWhiteboard.substring(
						model.selectedWhiteboard.lastIndexOf('/') +1 ); 
				isNewWhiteboard = false;
			}
			
			pbie = new PBInitiationEvent(
					model.selectedModel, 
					model.selectedDiagram, 
					model.isPopulate, 
					model.isCreateWhiteboard,
					iProject.getName(),
					model.title + POSTERBOARD_EXT,
					wbName, 
					isNewWhiteboard);
			EventManager.getInstance().dispatchEventSynchronous(pbie, true);

			if(pbie.isOpSuccessful()){
				List<IFile> filesToPublish = new ArrayList<IFile>();
				
				if(model.selectedModel != null && model.selectedDiagram != null) {
					filesToPublish.add(
							getFileFromWorkspaceRoot(model.selectedModel));
					filesToPublish.add(
							getFileFromWorkspaceRoot(model.selectedDiagram));
				}
				
				if(model.isCreateWhiteboard) {
					if(model.selectedWhiteboard == null)
						filesToPublish.add(getFileFromProject(pbie.getWhiteboardDiagramFile(), iProject));
					else
						filesToPublish.add(getFileFromWorkspaceRoot(model.selectedWhiteboard));
				}
				
				IFile pbIFile = getFileFromProject(pbie.getPbFile(), iProject); 
				filesToPublish.add(pbIFile);
				
				FilePublisherUtil.publishFiles(filesToPublish);

//				if (pbie.isWhiteboard()){
//					IFile wbIFile = getFileFromProject(pbie.getWhiteboardDiagramFile(), iProject);
//					openEditor(wbIFile, WHITEBOARD_ID);
//				}

				if (pbie.isShouldOpenPosterBoard()) {
					openEditor(pbIFile, POSTERBOARD_ID);
				}
				
			}
		} else {
			// error message
		}
	
		return true;
		
	}

	private void setView() {
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IViewPart view = page.findView("edu.mse.camel.client.playback.views.PlaybackView");
		if(view != null)
			page.hideView(view);
		try {
			page.showView("edu.mse.camel.client.chat.views.ChatView");
		} catch (PartInitException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private IFile getFileFromProject(String fileName, IProject project) {
		if (fileName != null) {
			IFile iFile = project.getFile(fileName);
			if (iFile.exists()) {
				return iFile;
			}
		}
		return null;
	}

	private void openEditor(IFile pbIFile, String editorID) {
		IWorkbenchPage page =
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		try {
			if (pbIFile.exists()) {
				IEditorInput editorInput = new FileEditorInput(pbIFile);
				page.openEditor(editorInput, editorID);
			}
		} catch (PartInitException e) {
			e.printStackTrace();
		}		
	}

	private IFile getFileFromWorkspaceRoot(String fileName) {
		if (fileName != null) {
			IFile iFile = root.getFile(new Path(fileName));
			if (iFile.exists()) {
				return iFile;
			}
		}
		return null;
	}
	
	private String getProjectName() {
		StringBuilder projectName = new StringBuilder(model.title);
		projectName.append(PROJECT_NAME_SEPARATOR);
		projectName.append(TeamList.getInstance().getMe().getName());
		projectName.append(PROJECT_NAME_SEPARATOR);
		DateFormat dateFormat = new SimpleDateFormat(
				"yyyy" + PROJECT_NAME_SEPARATOR + 
				"MM" + PROJECT_NAME_SEPARATOR + 
				"dd");
        Date date = new Date();
        projectName.append(dateFormat.format(date));
        
        IProject iProject = null;
        String returned = null;
        int i = 0;
        do {
        	String counter = Integer.toString(++i);
        	returned = projectName.toString() + PROJECT_NAME_SEPARATOR + counter;
        	iProject = root.getProject(returned);        	
        } while (iProject.exists());
        
        return returned.toString();
	}
	
	private IProject createTempProject() {
		
		String projectName = getProjectName();
		IProject project = root.getProject(projectName);
		IProjectDescription desc = root.getWorkspace().newProjectDescription(projectName);

//		System.out.println("modelname="+model.selectedModel);
		
		try {
			project.create(desc, null);
			project.open(null);
			
			// only make copies of files if they are not null
			if (model.selectedModel != null && model.selectedDiagram != null) {
				model.selectedModel = 
					copyFileToTempProject(model.selectedModel, projectName, root);
				
				model.selectedDiagram = 
					copyFileToTempProject(model.selectedDiagram, projectName, root);
			}			
			
			if (model.selectedWhiteboard != null) {
				model.selectedWhiteboard = 
					copyFileToTempProject(model.selectedWhiteboard, projectName, root);
			}
			
		} catch (CoreException e) {
			e.printStackTrace();
			project = null;
		}
		return project;
	}

	private String copyFileToTempProject(
			String selectedModel, String projectName, IWorkspaceRoot root) {
		IPath location = new Path(selectedModel);
		IFile iFile = root.getFile(location);
		try {
			String newModel = "/" + projectName + "/" + location.lastSegment();
			iFile.copy(
					new Path(newModel), false, new NullProgressMonitor());
			return newModel;
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String getWindowTitle() {
		return "New session";
	}
	
}
